const DURATION = 2000

let lastSrcs: string[] | undefined // 上一次获取到的src地址
// eslint-disable-next-line no-useless-escape
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm

async function extractNewScripts(): Promise<string[]> {
  const html = await fetch('/regionadm/' + '?_timestamp=' + Date.now()).then((resp) => {
    return resp.text()
  })
  scriptReg.lastIndex = 0
  const result: string[] = []
  let match: RegExpExecArray | null

  while ((match = scriptReg.exec(html)) !== null) {
    if (match.groups?.src) {
      result.push(match.groups.src)
    }
  }

  return result
}

async function needUpdate() {
  const newScripts = await extractNewScripts()
  if (!lastSrcs) {
    lastSrcs = newScripts
    return false
  }

  let result = false

  if (lastSrcs.length !== newScripts.length) {
    return true
  }
  for (let i = 0; i < lastSrcs.length; i++) {
    if (lastSrcs[i] !== newScripts[i]) {
      result = true
      break
    }
  }
  lastSrcs = newScripts
  return result
}

function autoRefresh() {
  setTimeout(async () => {
    const willUpdate = await needUpdate()
    if (willUpdate) {
      const result = confirm('系统有更新，点击确定刷新页面')
      if (result) {
        location.reload()
      }
    }
    autoRefresh()
  }, DURATION)
}

autoRefresh()
